//
// Created by tang on 3/6/23.
//

#include "service/svc_manager.hpp"
#include <cstring>
#include "core/assert.hpp"

static IService *services[(uint32_t) service_type::count] = {0};

IService::~IService () {}

ServiceManager::ServiceManager ()
{
    memset (services, 0, sizeof (services));
}
ServiceManager::~ServiceManager ()
{
    clear();
}

ServiceManager *ServiceManager::instance ()
{
    static ServiceManager inst;
    return &inst;
}
ServiceManager *ServiceManager::register_service (IService *svc)
{
    PI_ASSERT (svc != nullptr);
    service_type type = svc->get_type ();
    u32          idx  = (u32) type;
    PI_ASSERT_MSG (services[idx] == nullptr, "DUPLICATE service type %d", idx);
    services[idx] = svc;
    return this;
}

IService *ServiceManager::request_service (service_type type)
{
    u32 idx = (u32) type;
    PI_ASSERT_MSG (idx <= (u32) service_type::count, "TYPE out of range!!");
    return services[idx];
}

void ServiceManager::clear () {
    for (auto &x: services) {
        delete x;
        x = nullptr;
    }
}
